package com.mall.controller;

import com.mall.common.model.GlobalResponse;
import com.mall.consts.MallConst;
import com.mall.enums.GlobalResponseEnum;
import com.mall.form.UserLoginForm;
import com.mall.form.UserRegisterForm;
import com.mall.pojo.User;
import com.mall.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private IUserService userService;

    @PostMapping("/register")
    public GlobalResponse<User> register(@Valid @RequestBody UserRegisterForm userForm) {
        User user = new User();
        BeanUtils.copyProperties(userForm, user);
        return userService.register(user);
    }

    @PostMapping("/login")
    public GlobalResponse<User> login(@Valid @RequestBody UserLoginForm userLoginForm,
                                      HttpSession session){
        GlobalResponse<User> globalResponse = userService.login(userLoginForm.getUsername(), userLoginForm.getPassword());
        /*设置session*/
        session.setAttribute(MallConst.CURRENT_USER,globalResponse.getData());
        return globalResponse;
    }

    @GetMapping
    public GlobalResponse<User> userInfo(HttpSession session){
        User user = (User) session.getAttribute(MallConst.CURRENT_USER);
//        log.info("userInfo#user:{}",user);
        return GlobalResponse.successByData(user);
    }

    @PostMapping("/logout")
    public GlobalResponse logout(HttpSession session){
        session.removeAttribute(MallConst.CURRENT_USER);
        return GlobalResponse.success();
    }

}
